<template>
  <div>
    <div class="menu">
      <!-- element-plus > 2 -->
      <el-menu
        :default-active="activeRouter"
        class="el-menu-vertical-demo MainMenu tac"
        background-color="#181B39"
        text-color="#fff"
        :key="defaultKey"
        :collapse="isCollapse"
        :default-openeds="openeds"
        router
      >
        <div v-for="route in menuListData" :key="route.id">
          <el-menu-item v-if="!route?.children?.length" :index="route?.router">{{route?.name}}</el-menu-item>
          <el-sub-menu v-else :index="route.id">
            <template #title>
              <!-- <el-icon><Setting /></el-icon>使用的时候需要字体不能设置为18px,包的bug -->
              <span :style="{'overflow': isCollapse ? 'hidden' : 'unset'}">{{ route?.name }}</span>
            </template>
            <MenuList :activeRouter="activeRouter" @changeActiveRouter="changeActiveRouter" :menuListData="route?.children"></MenuList>
          </el-sub-menu>
        </div>
      </el-menu>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import _ from 'lodash'
import ElConfigProvider from 'element-plus'
import { RelativeActiveUrlMap } from '@/router/activeSeRouter'
import MenuList from './MenuList.vue'

export default defineComponent({
  name: 'ifMenu',
  props: {
    menuList: {
      type: Array as PropType<any[]>,
      required: true,
      default: () => [],
    },
    openMenu: {
      type: Boolean
    },
    isCollapse: {
      type: Boolean
    }
  },
  components: {
    [(ElConfigProvider as any).name]: ElConfigProvider,
    MenuList
  },
  setup(props) {
    const activeRouter = ref<string>('')
    const defaultMenuLevel = ref<number>(3)
    const defaultKey = ref<number>(0)
    const route = useRoute()
    const store = useStore()
    const openeds = ref()
    const menuData = _.cloneDeep(store.state.menuList)
    // 将pageRouter=1的 menu过滤掉
    const filterMenuList = (arr: any) => {
      const inner = (iarr: any): void => {
        [...iarr].forEach((item: Record<string, any>) => {
          if (item?.pageRouter === 0) {
            const index = iarr.findIndex((s: any) => s.router === item.router)
            iarr.splice(index, 1)[0]?.router
          }
          if (item?.children?.length) {
            inner(item.children)
          }
        })
      }
      inner(arr)
      return arr
    }
    filterMenuList(menuData)
    // 路由切换, call 两次
    const getInitMenuLevel = () => {
      const levelOne: Array<string> = menuData.map((item: any, index: any) => {
        return {
          router: item?.router,
          index
        }
      })
      const activeLevelOneRouter: string = `/${activeRouter.value.split('/').filter(Boolean)[0] as string}` || ''
      if (activeLevelOneRouter) {
        for (let i = 0; i < levelOne.length; i += 1) {
          const item: any = levelOne[i]
          if (item?.router === activeLevelOneRouter) {
            openeds.value = [item?.index]
          }
        }
      }
      if (!openeds.value) {
        openeds.value = [0]
      }
    }
    activeRouter.value = route.path
    getInitMenuLevel()
    // 监听菜单和路由
    watch([() => route.path], ([path]) => {
      const firstLevelArr: any = []
      menuData.forEach((item: any) => {
        item.children && item?.children.forEach((sItem: any) => {
          firstLevelArr.push(sItem?.router)
        })
      })
      // console.log(firstLevelArr)
      if (!firstLevelArr.includes(path)) {
        for (const key in RelativeActiveUrlMap) {
          // eslint-disable-next-line no-prototype-builtins
          if (RelativeActiveUrlMap.hasOwnProperty(key)) {
            const rootLevel: string = key
            const childrenLevel = RelativeActiveUrlMap[key]
            if (typeof childrenLevel === 'object') {
              const target = childrenLevel.find((url: string) => {
                return path.includes(url)
              })
              if (target) {
                activeRouter.value = rootLevel
                break
              }
            } else if (childrenLevel.includes(path)) {
              activeRouter.value = rootLevel
              break
            } else {
              activeRouter.value = path
            }
          }
        }
      } else {
        activeRouter.value = path
      }
      // 隐藏路由激活对应root路由
      for (const key in RelativeActiveUrlMap) {
        // eslint-disable-next-line no-prototype-builtins
        if (RelativeActiveUrlMap.hasOwnProperty(key)) {
          const rootLevel: string = key
          if (route.fullPath === rootLevel) {
            activeRouter.value = rootLevel
            break
          }
        }
      }
    }, { immediate: true })
    const showOrHideArrow = computed(() => (props.isCollapse ? 'none' : 'unset'))
    const changeActiveRouter = (router: string) => {
      activeRouter.value = router
    }
    return {
      activeRouter,
      openeds,
      defaultMenuLevel,
      defaultKey,
      showOrHideArrow,
      RelativeActiveUrlMap,
      menuListData: menuData,
      // methods
      changeActiveRouter
    }
  },
})
</script>

<style scoped lang="less">
.el-main-box {
  height: 100%;
  width: 100%;
  overflow: hidden;
  .menu {
    float: left;
    height: 100%;
    width: 90px;
    background: #fff;
    border-right: 1px solid rgba(0, 0, 0, 0.1);
  }
  .container {
    height: 100%;
    width: calc(100vw - 91px);
    float: right;
    box-sizing: border-box;
    padding: 14px;
  }
  .el-menu-item {
    padding-top: 10px;
    text-align: center;
    height: 65px;
    line-height: 24px;
    color: rgba(0, 0, 0, 0.5);
  }
  .el-menu {
    border: none !important;
  }
  .menu-box {
    padding-top: 8px;
    display: flex;
    flex-flow: column;
    flex-wrap: wrap;
    transition: color 0.25s;
  }
  .iconfont {
    font-size: 28px;
  }
  .is-active {
    color: #47c6a2;
  }
}

.app-title {
  height: 80px;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  .sys-title{
    font-size: 18px;
    background: #181B39;
    color: aliceblue;
    img {
      width: 32px;
      height: 32px;
      margin-right: 10px;
      vertical-align: middle;
    }
    span{
      vertical-align: middle;
    }
  }
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
}
:deep(.el-sub-menu .el-sub-menu__icon-arrow) {
  display: v-bind(showOrHideArrow);
}
</style>
